package com.atguigu.eduService.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduService.entity.EduSubject;
import com.atguigu.eduService.entity.excel.SubjectData;
import com.atguigu.eduService.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;

/**
 * @author Summerday
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService eduSubjectService;

    public SubjectExcelListener() {

    }

    //SubjectExcelListener不能交给spring进行管理,需要自己new,不能注入其他对象,不能实现数据库操作
    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    //读取excel中的内容,一行一行
    @SneakyThrows
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new Exception("文件上传数据不存在");
        }
        EduSubject existFirstSubject = existFirstSubject(eduSubjectService, subjectData.getFirstSubject());
        if (existFirstSubject == null) {
            //没有相同一级分类,添加
            existFirstSubject = new EduSubject();
            existFirstSubject.setParentId("0");
            existFirstSubject.setTitle(subjectData.getFirstSubject());
            eduSubjectService.save(existFirstSubject);
        }
        String pid = existFirstSubject.getId();
        EduSubject existSecondSubject = existSecondSubject(eduSubjectService, subjectData.getSecondSubject(), pid);
        if (existSecondSubject == null) {
            //没有相同一级分类,添加
            existSecondSubject = new EduSubject();
            existSecondSubject.setParentId(pid);
            existSecondSubject.setTitle(subjectData.getSecondSubject());
            eduSubjectService.save(existSecondSubject);
        }


    }

    //判断一级分类不能重复添加
    private EduSubject existFirstSubject(EduSubjectService eduSubjectService, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        return eduSubjectService.getOne(wrapper);
    }

    //判断二级分类不能重复添加
    private EduSubject existSecondSubject(EduSubjectService eduSubjectService, String name, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        return eduSubjectService.getOne(wrapper);
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
